package com.engine.camci.utils;

import org.apache.axis.encoding.Base64;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.docs.webservices.DocAttachment;
import weaver.docs.webservices.DocInfo;
import weaver.docs.webservices.DocServiceImpl;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.request.RequestComInfo;
import weaver.workflow.workflow.WorkflowComInfo;

import java.util.*;

/**
 * @Title: ecology-idea
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2022-06-22
 * @Description: ${description}
 * @ModifyLog:
 **/

public class CamciUtil {
    /**
     * @Description:--当月总计个税 当月总计个税计算公式（E2=【当月累计实发评审费】）：
     * E2<=800：0,
     * IF(E2<=3360：20%*(E2-800)/(1-20%),
     * IF(E2<=21000：(E2*(1-20%))/(1-20%*(1-20%))*20%,
     * IF(E2<=49500：((E2-2000)*(1-20%))/(1-30%*(1-20%))*30%-2000,
     * ((E2-7000)*(1-20%))/(1-40%*(1-20%))*40%-7000))))
     */
    public static String curmonthTaxTotal(String ffjes) {
        String curmonthTaxTotal = "";
        if (CalUtil.fCompare( ffjes, "800" ) <= 0) {
            curmonthTaxTotal = "0";
        } else if (CalUtil.fCompare( ffjes, "3360" ) <= 0) {
            String temp = CalUtil.fMultiply( "0.2", CalUtil.fSubtract( ffjes, "800" ), 2 );
            curmonthTaxTotal = CalUtil.fDivide( temp, CalUtil.fSubtract( "1", "0.2" ), 2 );
        } else if (CalUtil.fCompare( ffjes, "21000" ) <= 0) {
            String temp = CalUtil.fMultiply( ffjes, CalUtil.fSubtract( "1", "0.2" ), 2 );
            String temp1 = CalUtil.fSubtract( "1", CalUtil.fMultiply( "0.2", CalUtil.fSubtract( "1", "0.2" ), 2 ) );
            curmonthTaxTotal = CalUtil.fMultiply( CalUtil.fDivide( temp, temp1, 2 ), "0.2", 2 );
        } else if (CalUtil.fCompare( ffjes, "49500" ) <= 0) {
            String temp = CalUtil.fMultiply( CalUtil.fSubtract( ffjes, "2000" ), CalUtil.fSubtract( "1", "0.2" ), 2 );
            String temp1 = CalUtil.fSubtract( "1", CalUtil.fMultiply( "0.3", CalUtil.fSubtract( "1", "0.2" ), 2 ) );
            curmonthTaxTotal = CalUtil.fSubtract( CalUtil.fMultiply( CalUtil.fDivide( temp, temp1 ), "0.3", 2 ), "2000" );
        } else {
            String temp = CalUtil.fMultiply( CalUtil.fSubtract( ffjes, "7000" ), CalUtil.fSubtract( "1", "0.2" ), 2 );
            String temp1 = CalUtil.fSubtract( "1", CalUtil.fMultiply( "0.4", CalUtil.fSubtract( "1", "0.2" ), 2 ) );
            curmonthTaxTotal = CalUtil.fSubtract( CalUtil.fMultiply( CalUtil.fDivide( temp, temp1 ), "0.4", 2 ), "7000" );
        }
        return curmonthTaxTotal;
    }

    /*
     *@Description:创建文档
     */
    public static int createDoc(String rawFileName, byte[] content, int secid) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog( ">>>>>>createDocs>>>>>>" );
        int docid = -1;
        DocServiceImpl docserviceimpl = new DocServiceImpl();
        DocInfo doc = new DocInfo(); //创建文档
        String keyword = ""; //文档内容
        try {
            DocAttachment[] docattachment = new DocAttachment[1];
            baseBean.writeLog( ">>>>>rawFileName=" + rawFileName );
            String filetype = "";
            if (rawFileName.lastIndexOf( "." ) > -1) {
                filetype = rawFileName.substring( rawFileName.lastIndexOf( "." ) + 1 );
            }
            // 上传附件，创建html文档
            DocAttachment da = new DocAttachment();
            da.setFilename( rawFileName );//附件标题
            da.setFilecontent( Base64.encode( content ) ); //附件内容
            da.setFiletype( filetype ); //imagefiletype
            da.setImagefilename( rawFileName );// 附件标题
            da.setIszip( 1 );//是否压缩
            da.setIsAesEncrype( 0 );//是否加密
            da.setAesCode( "0" );
            da.setIsextfile( "1" ); //附件是否是office类型

            if (filetype.equalsIgnoreCase( "doc" )) {
                da.setDocfiletype( "3" );
            } else if (filetype.equalsIgnoreCase( "xls" )) {
                da.setDocfiletype( "4" );
            } else if (filetype.equalsIgnoreCase( "ppt" )) {
                da.setDocfiletype( "5" );
            } else if (filetype.equalsIgnoreCase( "wps" )) {
                da.setDocfiletype( "6" );
            } else if (filetype.equalsIgnoreCase( "docx" )) {
                da.setDocfiletype( "7" );
            } else if (filetype.equalsIgnoreCase( "xlsx" )) {
                da.setDocfiletype( "8" );
            } else if (filetype.equalsIgnoreCase( "pptx" )) {
                da.setDocfiletype( "9" );
            } else {
                da.setDocfiletype( "2" );
            }
            docattachment[0] = da;
            keyword = rawFileName;
            doc.setAttachments( docattachment );
            doc.setSeccategory( secid );//子目录id
            doc.setDocSubject( keyword );//标题
            doc.setDoccontent( "" );//文档内容
            /*文档属性*/
            doc.setDocType( 1 );
            //文档状态
            doc.setDocStatus( 1 );
            doc.setDocStatusStr( "正常" );
            //新闻类型
            doc.getDocPublishType();
            doc.setPublishable( "文档" );
            doc.setKeyword( keyword );
            docid = docserviceimpl.createDocByUser( doc, new User( 1 ) );
            baseBean.writeLog( ">>>>>docid=" + docid );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return docid;
    }

    /*
     *@Description:创建流程方法
     */
    public static String WorkflowCreateByRequestMap(String creatorId, String workflowId, String requestName, String IsNextFlow, Map<String, String> requestMainMap) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog( "-----创建流程传递的参数个数--------" );
        baseBean.writeLog( "creatorId:" + creatorId );
        baseBean.writeLog( "workflowId:" + workflowId );
        baseBean.writeLog( "requestName:" + requestName );
        baseBean.writeLog( "IsNextFlow:" + IsNextFlow );

        String requestid = "";
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setCreatorid( creatorId );//创建人Id
        requestInfo.setWorkflowid( workflowId );//工作流Id
        requestInfo.setDescription( requestName );//请求标题
        if ("0".equals( IsNextFlow )) {
            requestInfo.setIsNextFlow( IsNextFlow );
        }

        //主表字段
        MainTableInfo mainTableInfo = new MainTableInfo();
        Property[] propertyArray = new Property[requestMainMap.size()];
        int p = 0;
        for (Map.Entry<String, String> entry : requestMainMap.entrySet()) {
            propertyArray[p] = new Property();
            propertyArray[p].setName( Util.null2String( entry.getKey() ) );
            propertyArray[p].setValue( Util.null2String( entry.getValue() ) );
            baseBean.writeLog( "\r\n---p=" + p + "---Key=" + entry.getKey() + "---Value=" + entry.getValue() );
            p++;
        }
        baseBean.writeLog( "-----创建流程传递的参数个数p=" + p );
        mainTableInfo.setProperty( propertyArray );
        requestInfo.setMainTableInfo( mainTableInfo );
        RequestService service = new RequestService();
        try {
            //流程
            try {
                requestid = service.createRequest( requestInfo );//创建请求id
            } catch (Exception e) {
                baseBean.writeLog( "=======" + e.getMessage() );
            }
            //String userId = requestInfo.getLastoperator();//请求最后的操作者
            //记录日志
            StringBuffer sbf = new StringBuffer( "\r\n-----xwd创建工作流记录日志开始" );
            WorkflowComInfo wfcif = new WorkflowComInfo();
            RequestComInfo rcif = new RequestComInfo();
            ResourceComInfo rscif = new ResourceComInfo();
            sbf.append( "\r\n-----姓名:" + rscif.getLastname( rcif.getRequestCreater( requestid ) ) );
            sbf.append( "\r\n-----时间:" + rcif.getRequestCreateTime( requestid ) );
            sbf.append( "\r\n-----创建流程:" + wfcif.getWorkflowname( workflowId ) );
            sbf.append( "\r\n-----请求:" + rcif.getRequestname( requestid ) );
            sbf.append( "\r\n-----请求:" + requestid );
            sbf.append( "\r\n-----创建工作流记录日志结束" );
            baseBean.writeLog( sbf.toString() );
        } catch (Exception e) {
            baseBean.writeLog( "错误：" + e );
        }
        return requestid;
    }

    /*
     *@Description:根据requestid获取mainid
     */
    public static String getIdByRequestid(String requestid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select id from formtable_main_5 where requestid=?", requestid );
        rs.next();
        String id = Util.null2String( rs.getString( "id" ) );
        return id;
    }

    /*
     *@Description:建模权限重构
     */
    public static void getNewModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight( true );
        modeRightInfo.editModeDataShare( userid, formmodeid, id );
    }

    /*
     *@Description: 将数据插入表单建模
     */
    public static int insertModelData(int modeid, int userid, Map map) {
        int dataid = 0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        String sql = "select b.tablename,a.formid from modeinfo a left join workflow_bill b on a.formid=b.id where a.id=?";
        rs.executeQuery( sql, modeid );
        rs.next();
        String tablename = Util.null2String( rs.getString( "tablename" ) );
        String uuid = UUID.randomUUID().toString();
        String insSql = "insert into " + tablename
                + "(uuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
        Object[] params = {uuid, userid, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), modeid};
        if (rs.executeUpdate( insSql, params )) {
            rs1.executeQuery( "select id from " + tablename + " where uuid=?", uuid );
            rs1.next();
            dataid = Util.getIntValue( rs1.getString( "id" ) );
            if (dataid > 0) {
                //遍历数据 进行update
                String updatesql = "update " + tablename + " set ";
                Set<String> keySet = map.keySet();
                for (String key : keySet) {
                    updatesql += key + "='" + map.get( key ).toString() + "',";
                }
                if (updatesql.endsWith( "," )) {
                    updatesql = updatesql.substring( 0, updatesql.length() - 1 );
                    updatesql += " where id=" + dataid;
                    rs.executeUpdate( updatesql );
                }
                //进行权限重构
                getNewModeRight( userid, modeid, dataid );
            }
        }
        return dataid;
    }

    /*
     *@Description: 创建流程
     */
    public static String createWorkflow(User user, String docids, List<Map<String, Object>> requestMainMapList) {
        int userid = user.getUID();
        String curdate = DateUtil.getCurrentDate();
        String username = user.getLastname();
        String formid = "5";
        Map<String, String> wf = getWorkflowId(formid);
        String workflowname = Util.null2String(wf.get("workflowname"));
        String requestname = workflowname+"-" + username + "-" + curdate;
        String workflowid = Util.null2String(wf.get("workflowid"));
        RecordSet rs = new RecordSet();
        Map<String, String> requestMainMap = new HashMap<>();
        requestMainMap.put( "zdr", userid + "" );
        requestMainMap.put( "zdrq", curdate );
        requestMainMap.put( "fj", docids );
        String requestid = CamciUtil.WorkflowCreateByRequestMap( userid + "", workflowid, requestname, "0", requestMainMap );
        if (Util.getIntValue( requestid ) > 0) {
            String mainid = getIdByRequestid( requestid );
            for (Map<String, Object> map : requestMainMapList) {
                String xm = Util.null2String( map.get( "xm" ) );
                String sfzh = Util.null2String( map.get( "sfzh" ) );
                String sfje = Util.null2String( map.get( "sfje" ) );
                String dkgs = Util.null2String( map.get( "dkgs" ) );
                String yfje = Util.null2String( map.get( "yfje" ) );
                String sql = "insert into formtable_main_5_dt1 (mainid,xm,sfzh,yfje,dkgs,sfje) values(?,?,?,?,?,?)";
                rs.executeUpdate( sql, new Object[]{mainid, xm, sfzh, yfje, dkgs, sfje} );
            }
        }
        return requestid;
    }

    /*
     *@Description: 获取根据人员获取所有参与会议的评审费
     */
    public static Map<String, Object> getPsfBySfzh(String hymcs, String sfzh) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select sfzh,sum(ffje) as ffjes from formtable_main_4_dt1 t1 " +
                "where hymc in (" + hymcs + ") and sfzh=? group by sfzh", sfzh );
        Map<String, Object> dataMap = new HashMap<>();
        if (rs.next()) {
            String ffjes = Util.null2String( rs.getString( "ffjes" ) );
            String yjgs = curmonthTaxTotal( ffjes );
            String yfpsf = CalUtil.fAdd( ffjes, yjgs );
            dataMap.put( "yfpsf", yfpsf );
            dataMap.put( "sfpsf", ffjes );
            dataMap.put( "yjgs", yjgs );
        }
        return dataMap;
    }

    /*
     *@Description: 获取会议的代扣个税根据身份证号
     */
    public static String getDkgsBySfzh(String hymcs, String sfzh) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select hymc,ffje," +
                " CHARINDEX(',' + CONVERT(VARCHAR(10), hymc) + ',', '," + hymcs + ",') AS idindex" +
                " from formtable_main_4_dt1 where hymc in (" + hymcs + ") and sfzh=? " +
                "order by idindex,sfzh", sfzh );
        String lastffje = "0";
        String lastdkgs = "0";
        String returndkgs = "";
        while (rs.next()) {//1,2,3
            String ffje = Util.null2String( rs.getString( "ffje" ) );//2000,900,7000
            lastffje = CalUtil.fAdd( lastffje, ffje );//0+2000,2900,9900
            String dkgs = curmonthTaxTotal( lastffje );//300,525,1886.71
            returndkgs = CalUtil.fSubtract( dkgs, lastdkgs );//300-0,525-300,1886.71-525
            lastdkgs = CalUtil.fAdd( lastdkgs, returndkgs );//300+0,300+225,1360.71
            rs.writeLog( "ffje=" + ffje + ",lastffje=" + lastffje + ",dkgs=" + dkgs + ",returndkgs=" + returndkgs + ",lastdkgs=" + lastdkgs );
        }
        rs.writeLog( "returndkgs=" + returndkgs );
        return returndkgs;
    }


    /**
     * @Description: 获取最新版本号的workflowid
     * @Param: [formid]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2022/9/6
     */
    public static Map<String, String> getWorkflowId(String formid) {
        RecordSet rs = new RecordSet();
        Map<String, String> resultMap = new HashMap<>();
        rs.executeQuery("select (case when activeversionid is null then id else activeversionid end) from workflow_base " +
                "where abs(formid)=? group by (case when activeversionid is null then id else activeversionid end) ", formid);
        rs.next();
        String workflowid = Util.null2String(rs.getString(1));
        resultMap.put("workflowid", workflowid);
        rs.executeQuery("select workflowname from workflow_base where id=?", workflowid);
        rs.next();
        String workflowname = Util.null2String(rs.getString(1));
        resultMap.put("workflowname", workflowname);
        return resultMap;
    }

    public static String getNodeidByHymc(String hymc) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select requestid from formtable_main_4 where hymc=?",hymc);
        rs.next();
        String requestid = Util.null2String(rs.getString("requestid"));
        rs.executeQuery("select nownodeid from workflow_nownode where requestid=?", requestid);
        rs.next();
        return Util.null2String(rs.getString("nownodeid"));
    }
    public static boolean containsStringArray(String[] array, String target) {
        return Arrays.asList(array).contains(target);
    }

}
